package com.xiaoxing.yunshu.mvp.ui.activity;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.res.ResourcesCompat;
import android.support.v4.view.ViewPager;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.model.LatLng;
import com.baidu.trace.api.entity.OnEntityListener;
import com.baidu.trace.api.fence.FenceAlarmPushInfo;
import com.baidu.trace.api.fence.MonitoredAction;
import com.baidu.trace.api.track.LatestPoint;
import com.baidu.trace.api.track.LatestPointResponse;
import com.baidu.trace.api.track.OnTrackListener;
import com.baidu.trace.model.LocationMode;
import com.baidu.trace.model.OnTraceListener;
import com.baidu.trace.model.PushMessage;
import com.baidu.trace.model.StatusCodes;
import com.baidu.trace.model.TraceLocation;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.base.BaseConstants;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.LogUtils;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.xiaoxing.yunshu.R;
import com.xiaoxing.yunshu.di.component.DaggerMainComponent;
import com.xiaoxing.yunshu.di.module.MainModule;
import com.xiaoxing.yunshu.mvp.contract.MainContract;
import com.xiaoxing.yunshu.mvp.presenter.MainPresenter;
import com.xiaoxing.yunshu.mvp.ui.adapter.MyViewPagerAdapter;
import com.xiaoxing.yunshu.mvp.ui.entity.GetDistributingCount;
import com.xiaoxing.yunshu.mvp.ui.receiver.TrackReceiver;
import com.xiaoxing.yunshu.mvp.ui.track.BitmapUtil;
import com.xiaoxing.yunshu.mvp.ui.track.CommonUtil;
import com.xiaoxing.yunshu.mvp.ui.track.Constants;
import com.xiaoxing.yunshu.mvp.ui.track.CurrentLocation;
import com.xiaoxing.yunshu.mvp.ui.track.MapUtil;
import com.xiaoxing.yunshu.mvp.ui.track.TrackApplication;

import org.simple.eventbus.Subscriber;
import org.simple.eventbus.ThreadMode;

import java.util.HashMap;

import me.jessyan.armscomponent.commonsdk.core.RouterHub;
import me.jessyan.armscomponent.commonsdk.utils.Utils;
import me.majiajie.pagerbottomtabstrip.NavigationController;
import me.majiajie.pagerbottomtabstrip.PageNavigationView;
import me.majiajie.pagerbottomtabstrip.SpecialTab;
import me.majiajie.pagerbottomtabstrip.SpecialTabRound;
import me.majiajie.pagerbottomtabstrip.item.BaseTabItem;

import static com.jess.arms.utils.Preconditions.checkNotNull;


@Route(path = RouterHub.APP_MAIN_ACTIVITY)
public class MainActivity extends BaseActivity<MainPresenter> implements MainContract.View, View.OnClickListener {

    /**
     * 打包周期
     */
    public int packInterval = Constants.DEFAULT_PACK_INTERVAL;
    private ViewPager viewPager;
    private TrackApplication trackApp = null;
    private Button traceBtn = null;
    private Button gatherBtn = null;
    private NotificationManager notificationManager = null;
    private PowerManager powerManager = null;
    private PowerManager.WakeLock wakeLock = null;
    private TrackReceiver trackReceiver = null;
    /**
     * 地图工具
     */
    private MapUtil mapUtil = null;
    /**
     * 轨迹服务监听器
     */
    private OnTraceListener traceListener = null;
    /**
     * 轨迹监听器(用于接收纠偏后实时位置回调)
     */
    private OnTrackListener trackListener = null;
    /**
     * Entity监听器(用于接收实时定位回调)
     */
    private OnEntityListener entityListener = null;
    /**
     * 实时定位任务
     */
    private RealTimeHandler realTimeHandler = new RealTimeHandler();
    private RealTimeLocRunnable realTimeLocRunnable = null;
    private boolean isRealTimeRunning = true;
    private int notifyId = 0;

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerMainComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .mainModule(new MainModule(this))
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_main; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {


        PageNavigationView tab = (PageNavigationView) findViewById(R.id.tab);

        NavigationController navigationController = tab.custom()
                .addItem(newItem(R.drawable.icon_tab001, R.drawable.icon_tab001, "抢单"))
                .addItem(newItem(R.drawable.icon_tab002, R.drawable.icon_tab002, "配送"))
                .addItem(newItem(R.drawable.icon_tab003, R.drawable.icon_tab003, "我的"))
//                .addItem(newRoundItem(R.drawable.fb_active_icon, R.drawable.fb_active_icon, ""))
//                .addItem(newItem(R.drawable.ic_menu_me, R.drawable.ic_menu_me, "历史预约"))
                .build();

        viewPager = (ViewPager) findViewById(R.id.viewPager);
        viewPager.setAdapter(new MyViewPagerAdapter(getSupportFragmentManager(), navigationController.getItemCount()));
        viewPager.setOffscreenPageLimit(4);
        //自动适配ViewPager页面切换
        navigationController.setupWithViewPager(viewPager);

        BitmapUtil.init();


        init();

        try {

            String entityname = mSharedPreferencesHelper.getString(BaseConstants.DISPLAY_NAME) + "_" + mSharedPreferencesHelper.getString(BaseConstants.MOBILE_PHONE);
            LogUtils.debugEInfo("entityname==" + entityname);
            //鹰眼轨迹服务在APP运行期间一直开启，进到主页即开始服务，这时候轨迹采集并没有开启，开始配送的时候启动采集轨迹，结束配送的时候结束采集轨迹，
            trackApp.mTrace.setEntityName(entityname);
            trackApp.mClient.startTrace(trackApp.mTrace, traceListener);
            if (Constants.DEFAULT_PACK_INTERVAL != packInterval) {
                stopRealTimeLoc();
                startRealTimeLoc(packInterval);
            }

            //延迟10s（是为了等待鹰眼服务开启）查询是否有进行中的任务，有任务即开始采集轨迹，没有结束一下采集轨迹。
            // 这个是因为有可能换手机，或者APP强制退出后，重新进入APP之后，继续执行轨迹采集工作。
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    LogUtils.debugEInfo("============getDistributingCount===============");
                    if (mPresenter != null)
                        mPresenter.getDistributingCount(new HashMap<>());
                }
            }, 1000 * 10);
        } catch (Exception e) {
            e.printStackTrace();
        }

//        checkTrackServiceIsBegin();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

            if (!mSharedPreferencesHelper.getBoolean(BaseConstants.YUN_XING_QUAN_XIAN)) {
                showQuanXianSheZhiDialog();
            }
        }


    }

    /**
     * 正常tab
     */
    private BaseTabItem newItem(int drawable, int checkedDrawable, String text) {
        SpecialTab mainTab = new SpecialTab(this);
        mainTab.initialize(drawable, checkedDrawable, text);
        mainTab.setTextDefaultColor(getResources().getColor(R.color.public_white));
        mainTab.setTextCheckedColor(getResources().getColor(R.color.public_white));
        return mainTab;
    }

    private void init() {
        initListener();
        trackApp = (TrackApplication) getApplicationContext();
        mapUtil = MapUtil.getInstance();
        mapUtil.init((MapView) findViewById(R.id.tracing_mapView));
        mapUtil.setCenter(trackApp);
        startRealTimeLoc(Constants.LOC_INTERVAL);
        powerManager = (PowerManager) trackApp.getSystemService(Context.POWER_SERVICE);

        traceBtn = (Button) findViewById(R.id.btn_trace);
        gatherBtn = (Button) findViewById(R.id.btn_gather);

        traceBtn.setOnClickListener(this);
        gatherBtn.setOnClickListener(this);
        setTraceBtnStyle();
        setGatherBtnStyle();

        notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    }

    public void stopRealTimeLoc() {
        isRealTimeRunning = false;
        if (null != realTimeHandler && null != realTimeLocRunnable) {
            realTimeHandler.removeCallbacks(realTimeLocRunnable);
        }
        trackApp.mClient.stopRealTimeLoc();
    }

    public void startRealTimeLoc(int interval) {
        isRealTimeRunning = true;
        realTimeLocRunnable = new RealTimeLocRunnable(interval);
        realTimeHandler.post(realTimeLocRunnable);
    }

    private void showQuanXianSheZhiDialog() {
        new QMUIDialog.MessageDialogBuilder(this)
                .setTitle("权限设置，非常重要！！！")
                .setCanceledOnTouchOutside(false)
                .setMessage("请关闭自动管理，必须改为[手动管理]，允许自启动和后台活动，否则无法正常记录轨迹。如果没有开启后台运行权限，将可能导致记录异常、距离减少、轨迹无法记录等问题。")
                .addAction("取消", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                    }
                })
                .addAction(0, "去设置", QMUIDialogAction.ACTION_PROP_NEGATIVE, new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        Utils.navigation(MainActivity.this, RouterHub.ACTIVITY_QUAN_XIAN_SHE_ZHI);

                        dialog.dismiss();
                    }
                })
                .create(com.qmuiteam.qmui.R.style.QMUI_Dialog).show();
    }

    private void initListener() {

        trackListener = new OnTrackListener() {

            @Override
            public void onLatestPointCallback(LatestPointResponse response) {
                if (StatusCodes.SUCCESS != response.getStatus()) {
                    return;
                }

                LatestPoint point = response.getLatestPoint();
                if (null == point || CommonUtil.isZeroPoint(point.getLocation().getLatitude(), point.getLocation()
                        .getLongitude())) {
                    return;
                }

                LatLng currentLatLng = mapUtil.convertTrace2Map(point.getLocation());
                if (null == currentLatLng) {
                    return;
                }
                CurrentLocation.locTime = point.getLocTime();
                CurrentLocation.latitude = currentLatLng.latitude;
                CurrentLocation.longitude = currentLatLng.longitude;

                if (null != mapUtil) {
                    mapUtil.updateStatus(currentLatLng, true);
                }
            }
        };

        entityListener = new OnEntityListener() {

            @Override
            public void onReceiveLocation(TraceLocation location) {

                if (StatusCodes.SUCCESS != location.getStatus() || CommonUtil.isZeroPoint(location.getLatitude(),
                        location.getLongitude())) {
                    return;
                }
                LatLng currentLatLng = mapUtil.convertTraceLocation2Map(location);
                if (null == currentLatLng) {
                    return;
                }
                CurrentLocation.locTime = CommonUtil.toTimeStamp(location.getTime());
                CurrentLocation.latitude = currentLatLng.latitude;
                CurrentLocation.longitude = currentLatLng.longitude;

//                LogUtils.debugEInfo("latitude=" + currentLatLng.latitude + " longitude=" + currentLatLng.longitude);

                mSharedPreferencesHelper.putString("latitude", String.valueOf(currentLatLng.latitude));
                mSharedPreferencesHelper.putString("longitude", String.valueOf(currentLatLng.longitude));
                if (null != mapUtil) {
                    mapUtil.updateStatus(currentLatLng, true);
                }
            }

        };


        traceListener = new OnTraceListener() {

            /**
             * 绑定服务回调接口
             * @param errorNo  状态码
             * @param message 消息
             *                <p>
             *                <pre>0：成功 </pre>
             *                <pre>1：失败</pre>
             */
            @Override
            public void onBindServiceCallback(int errorNo, String message) {

                LogUtils.debugEInfo(String.format("onBindServiceCallback, errorNo:%d, message:%s ", errorNo, message));
            }

            /**
             * 开启服务回调接口
             * @param errorNo 状态码
             * @param message 消息
             *                <p>
             *                <pre>0：成功 </pre>
             *                <pre>10000：请求发送失败</pre>
             *                <pre>10001：服务开启失败</pre>
             *                <pre>10002：参数错误</pre>
             *                <pre>10003：网络连接失败</pre>
             *                <pre>10004：网络未开启</pre>
             *                <pre>10005：服务正在开启</pre>
             *                <pre>10006：服务已开启</pre>
             */
            @Override
            public void onStartTraceCallback(int errorNo, String message) {
                LogUtils.debugEInfo(String.format("onStartTraceCallback, errorNo:%d, message:%s ", errorNo, message));
                showMessage(String.format("开启服务：%s ", message));

                if (StatusCodes.SUCCESS == errorNo || StatusCodes.START_TRACE_NETWORK_CONNECT_FAILED <= errorNo) {
                    trackApp.isTraceStarted = true;
                    SharedPreferences.Editor editor = trackApp.trackConf.edit();
                    editor.putBoolean("is_trace_started", true);
                    editor.apply();
                    setTraceBtnStyle();
                    registerReceiver();
                }


            }

            /**
             * 停止服务回调接口
             * @param errorNo 状态码
             * @param message 消息
             *                <p>
             *                <pre>0：成功</pre>
             *                <pre>11000：请求发送失败</pre>
             *                <pre>11001：服务停止失败</pre>
             *                <pre>11002：服务未开启</pre>
             *                <pre>11003：服务正在停止</pre>
             */
            @Override
            public void onStopTraceCallback(int errorNo, String message) {
                LogUtils.debugEInfo(String.format("onStopTraceCallback, errorNo:%d, message:%s ", errorNo, message));
                showMessage(String.format("停止服务：%s ", message));

                if (StatusCodes.SUCCESS == errorNo || StatusCodes.CACHE_TRACK_NOT_UPLOAD == errorNo) {
                    trackApp.isTraceStarted = false;
                    trackApp.isGatherStarted = false;
                    // 停止成功后，直接移除is_trace_started记录（便于区分用户没有停止服务，直接杀死进程的情况）
                    SharedPreferences.Editor editor = trackApp.trackConf.edit();
                    editor.remove("is_trace_started");
                    editor.remove("is_gather_started");
                    editor.apply();
                    setTraceBtnStyle();
                    setGatherBtnStyle();
                    unregisterPowerReceiver();

                }

            }

            /**
             * 开启采集回调接口
             * @param errorNo 状态码
             * @param message 消息
             *                <p>
             *                <pre>0：成功</pre>
             *                <pre>12000：请求发送失败</pre>
             *                <pre>12001：采集开启失败</pre>
             *                <pre>12002：服务未开启</pre>
             */
            @Override
            public void onStartGatherCallback(int errorNo, String message) {
                LogUtils.debugEInfo(String.format("onStartGatherCallback, errorNo:%d, message:%s ", errorNo, message));
                showMessage(String.format("开启采集：%s ", message));

                if (StatusCodes.SUCCESS == errorNo || StatusCodes.GATHER_STARTED == errorNo) {
                    trackApp.isGatherStarted = true;
                    SharedPreferences.Editor editor = trackApp.trackConf.edit();
                    editor.putBoolean("is_gather_started", true);
                    editor.apply();
                    setGatherBtnStyle();
                }

            }

            /**
             * 停止采集回调接口
             * @param errorNo 状态码
             * @param message 消息
             *                <p>
             *                <pre>0：成功</pre>
             *                <pre>13000：请求发送失败</pre>
             *                <pre>13001：采集停止失败</pre>
             *                <pre>13002：服务未开启</pre>
             */
            @Override
            public void onStopGatherCallback(int errorNo, String message) {
                LogUtils.debugEInfo(String.format("onStopGatherCallback, errorNo:%d, message:%s ", errorNo, message));
                showMessage(String.format("停止采集：%s ", message));

                if (StatusCodes.SUCCESS == errorNo || StatusCodes.GATHER_STOPPED == errorNo) {
                    trackApp.isGatherStarted = false;
                    SharedPreferences.Editor editor = trackApp.trackConf.edit();
                    editor.remove("is_gather_started");
                    editor.apply();
                    setGatherBtnStyle();
                }


            }

            /**
             * 推送消息回调接口
             *
             * @param messageType 状态码
             * @param pushMessage 消息
             *                  <p>
             *                  <pre>0x01：配置下发</pre>
             *                  <pre>0x02：语音消息</pre>
             *                  <pre>0x03：服务端围栏报警消息</pre>
             *                  <pre>0x04：本地围栏报警消息</pre>
             *                  <pre>0x05~0x40：系统预留</pre>
             *                  <pre>0x41~0xFF：开发者自定义</pre>
             */
            @Override
            public void onPushCallback(byte messageType, PushMessage pushMessage) {

                LogUtils.debugEInfo(String.format("onPushCallback, messageType:%d, messageContent:%s ", messageType,
                        pushMessage));

                if (messageType < 0x03 || messageType > 0x04) {
                    showMessage(pushMessage.getMessage());
                    return;
                }
                FenceAlarmPushInfo alarmPushInfo = pushMessage.getFenceAlarmPushInfo();
                if (null == alarmPushInfo) {
                    LogUtils.debugEInfo(String.format("onPushCallback, messageType:%d, messageContent:%s ", messageType,
                            pushMessage));
                    return;
                }
                StringBuffer alarmInfo = new StringBuffer();
                alarmInfo.append("您于")
                        .append(CommonUtil.getHMS(alarmPushInfo.getCurrentPoint().getLocTime() * 1000))
                        .append(alarmPushInfo.getMonitoredAction() == MonitoredAction.enter ? "进入" : "离开")
                        .append(messageType == 0x03 ? "云端" : "本地")
                        .append("围栏：").append(alarmPushInfo.getFenceName());

                if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN) {
                    Notification notification = new Notification.Builder(trackApp)
                            .setContentTitle(getResources().getString(R.string.alarm_push_title))
                            .setContentText(alarmInfo.toString())
                            .setSmallIcon(R.mipmap.arms_log)
                            .setWhen(System.currentTimeMillis()).build();
                    notificationManager.notify(notifyId++, notification);
                }
            }

            @Override
            public void onInitBOSCallback(int errorNo, String message) {
                LogUtils.debugEInfo(String.format("onInitBOSCallback, errorNo:%d, message:%s ", errorNo, message));
            }
        };

    }

    /**
     * 设置服务按钮样式
     */
    private void setTraceBtnStyle() {
        boolean isTraceStarted = trackApp.trackConf.getBoolean("is_trace_started", false);
        if (isTraceStarted) {
            traceBtn.setText(R.string.stop_trace);
            traceBtn.setTextColor(ResourcesCompat.getColor(getResources(), R.color
                    .public_white, null));
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                traceBtn.setBackground(ResourcesCompat.getDrawable(getResources(),
                        R.mipmap.bg_btn_sure, null));
            } else {
                traceBtn.setBackgroundDrawable(ResourcesCompat.getDrawable(getResources(),
                        R.mipmap.bg_btn_sure, null));
            }
        } else {
            traceBtn.setText(R.string.start_trace);
            traceBtn.setTextColor(ResourcesCompat.getColor(getResources(), R.color.layout_title, null));
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                traceBtn.setBackground(ResourcesCompat.getDrawable(getResources(),
                        R.mipmap.bg_btn_cancel, null));
            } else {
                traceBtn.setBackgroundDrawable(ResourcesCompat.getDrawable(getResources(),
                        R.mipmap.bg_btn_cancel, null));
            }
        }
    }

    /**
     * 设置采集按钮样式
     */
    private void setGatherBtnStyle() {
        boolean isGatherStarted = trackApp.trackConf.getBoolean("is_gather_started", false);
        if (isGatherStarted) {
            gatherBtn.setText(R.string.stop_gather);
            gatherBtn.setTextColor(ResourcesCompat.getColor(getResources(), R.color.public_white, null));
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                gatherBtn.setBackground(ResourcesCompat.getDrawable(getResources(),
                        R.mipmap.bg_btn_sure, null));
            } else {
                gatherBtn.setBackgroundDrawable(ResourcesCompat.getDrawable(getResources(),
                        R.mipmap.bg_btn_sure, null));
            }
        } else {
            gatherBtn.setText(R.string.start_gather);
            gatherBtn.setTextColor(ResourcesCompat.getColor(getResources(), R.color.layout_title, null));
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                gatherBtn.setBackground(ResourcesCompat.getDrawable(getResources(),
                        R.mipmap.bg_btn_cancel, null));
            } else {
                gatherBtn.setBackgroundDrawable(ResourcesCompat.getDrawable(getResources(),
                        R.mipmap.bg_btn_cancel, null));
            }
        }
    }

    /**
     * 注册广播（电源锁、GPS状态）
     */
    @SuppressLint("InvalidWakeLockTag")
    private void registerReceiver() {
        if (trackApp.isRegisterReceiver) {
            return;
        }

        if (null == wakeLock) {
            wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "track upload");
        }
        if (null == trackReceiver) {
            trackReceiver = new TrackReceiver(wakeLock);
        }

        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        filter.addAction(Intent.ACTION_SCREEN_ON);
        filter.addAction(Intent.ACTION_USER_PRESENT);
        filter.addAction(StatusCodes.GPS_STATUS_ACTION);
        trackApp.registerReceiver(trackReceiver, filter);
        trackApp.isRegisterReceiver = true;

    }

    private void unregisterPowerReceiver() {
        if (!trackApp.isRegisterReceiver) {
            return;
        }
        if (null != trackReceiver) {
            trackApp.unregisterReceiver(trackReceiver);
        }
        trackApp.isRegisterReceiver = false;
    }

    @Subscriber(tag = "startYunShu", mode = ThreadMode.MAIN)
    public void startYunShu(String msg) {

//        String entityname = mSharedPreferencesHelper.getString(BaseConstants.DISPLAY_NAME) + "_" + mSharedPreferencesHelper.getString(BaseConstants.MOBILE_PHONE);
//        LogUtils.debugEInfo("entityname==" + entityname);
//        trackApp.mTrace.setEntityName(entityname);
//        trackApp.mClient.startTrace(trackApp.mTrace, traceListener);
//        if (Constants.DEFAULT_PACK_INTERVAL != packInterval) {
//            stopRealTimeLoc();
//            startRealTimeLoc(packInterval);
//        }

//        showMessage("轨迹搜集开始");
        trackApp.mClient.startGather(traceListener);
    }

    @Subscriber(tag = "endYunShu", mode = ThreadMode.MAIN)
    public void stopYingYan(String msg) {
        endYunShu();
    }

    private void endYunShu() {
//        trackApp.isTraceStarted = true;
//        if (trackApp.isTraceStarted) { //结束配送，停止轨迹服务：此方法将同时停止轨迹服务和轨迹采集，完全结束鹰眼轨迹服务
//            trackApp.mClient.stopTrace(trackApp.mTrace, traceListener);
//            stopRealTimeLoc();
//        }
        trackApp.mClient.stopGather(traceListener);
    }

    @Subscriber(tag = "setMainCurrentItem", mode = ThreadMode.MAIN)
    public void setMainCurrentItem(int position) {
        viewPager.setCurrentItem(position);
    }

    /**
     * 圆形tab
     */
    private BaseTabItem newRoundItem(int drawable, int checkedDrawable, String text) {
        SpecialTabRound mainTab = new SpecialTabRound(this);
        mainTab.initialize(drawable, checkedDrawable, text);
        mainTab.setTextDefaultColor(getResources().getColor(R.color.public_white));
        mainTab.setTextCheckedColor(getResources().getColor(R.color.public_white));
        return mainTab;
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.makeText(this, message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            // 追踪选项设置
//            case R.id.btn_activity_options:
//                ViewUtil.startActivityForResult(this, TracingOptionsActivity.class, Constants
//                        .REQUEST_CODE);
//                break;

            case R.id.btn_trace:
                if (trackApp.isTraceStarted) {
                    trackApp.mClient.stopTrace(trackApp.mTrace, traceListener);
                    stopRealTimeLoc();
                } else {
                    trackApp.mClient.startTrace(trackApp.mTrace, traceListener);
                    if (Constants.DEFAULT_PACK_INTERVAL != packInterval) {
                        stopRealTimeLoc();
                        startRealTimeLoc(packInterval);
                    }
                }
                break;

            case R.id.btn_gather:
                if (trackApp.isGatherStarted) {
                    trackApp.mClient.stopGather(traceListener);
                } else {
                    trackApp.mClient.startGather(traceListener);
                }
                break;

            default:
                break;
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (null == data) {
            return;
        }

        if (data.hasExtra("locationMode")) {
            LocationMode locationMode = LocationMode.valueOf(data.getStringExtra("locationMode"));
            trackApp.mClient.setLocationMode(locationMode);
        }

        if (data.hasExtra("isNeedObjectStorage")) {
            boolean isNeedObjectStorage = data.getBooleanExtra("isNeedObjectStorage", false);
            trackApp.mTrace.setNeedObjectStorage(isNeedObjectStorage);
        }

        if (data.hasExtra("gatherInterval") || data.hasExtra("packInterval")) {
            int gatherInterval = data.getIntExtra("gatherInterval", Constants.DEFAULT_GATHER_INTERVAL);
            int packInterval = data.getIntExtra("packInterval", Constants.DEFAULT_PACK_INTERVAL);
            this.packInterval = packInterval;
            trackApp.mClient.setInterval(gatherInterval, packInterval);
        }

        //        if (data.hasExtra("supplementMode")) {
        //            mSupplementMode = SupplementMode.valueOf(data.getStringExtra("supplementMode"));
        //        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        mapUtil.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mapUtil.onResume();


        // 在Android 6.0及以上系统，若定制手机使用到doze模式，请求将应用添加到白名单。
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            String packageName = trackApp.getPackageName();
            boolean isIgnoring = powerManager.isIgnoringBatteryOptimizations(packageName);
            if (!isIgnoring) {
                Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
                intent.setData(Uri.parse("package:" + packageName));
                try {
                    startActivity(intent);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }

        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        startRealTimeLoc(packInterval);
    }

    @Override
    protected void onStop() {
        super.onStop();
//        stopRealTimeLoc();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
//            ExitUtil.exit(this);

            new QMUIDialog.MessageDialogBuilder(this)
                    .setTitle("确定退出APP?")
                    .setCanceledOnTouchOutside(false)
                    .setMessage("退出APP，将可能导致记录异常、距离减少、轨迹无法记录等问题。")
                    .addAction("取消", new QMUIDialogAction.ActionListener() {
                        @Override
                        public void onClick(QMUIDialog dialog, int index) {
                            dialog.dismiss();
                        }
                    })
                    .addAction(0, "确定", QMUIDialogAction.ACTION_PROP_NEGATIVE, new QMUIDialogAction.ActionListener() {
                        @Override
                        public void onClick(QMUIDialog dialog, int index) {
                            moveTaskToBack(false);
                            dialog.dismiss();
                        }
                    })
                    .create(com.qmuiteam.qmui.R.style.QMUI_Dialog).show();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            mapUtil.clear();

            trackApp.mClient.stopTrace(trackApp.mTrace, traceListener);
            stopRealTimeLoc();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void getDistributingCountSuccessed(GetDistributingCount entity) {

        if (entity != null && entity.getCode() == 200) {
            if (entity.getData() > 0) {

//                trackApp.isTraceStarted = true;
//                trackApp.isGatherStarted = true;
//                SharedPreferences.Editor editor = trackApp.trackConf.edit();
//                editor.putBoolean("is_trace_started", true);
//                editor.putBoolean("is_gather_started", true);
//                editor.apply();
//                checkTrackServiceIsBegin();
                trackApp.mClient.startGather(traceListener);
            } else if (entity.getData() == 0) {
                endYunShu();
//                if (trackApp.trackConf.contains("is_trace_started") && trackApp.isTraceStarted) {
//                    SharedPreferences.Editor editor = trackApp.trackConf.edit();
//                    editor.remove("is_trace_started");
//                    editor.apply();
//                    trackApp.isTraceStarted = false;
//                }
//                if (trackApp.trackConf.contains("is_gather_started") && trackApp.isGatherStarted) {
//                    SharedPreferences.Editor editor = trackApp.trackConf.edit();
//                    editor.remove("is_gather_started");
//                    editor.apply();
//                    trackApp.isGatherStarted = false;
//                }
//


            }
        }
    }

    private void checkTrackServiceIsBegin() {
        showMessage("轨迹服务正在开启...");
        if (trackApp.trackConf.contains("is_trace_started") && trackApp.trackConf.contains("is_gather_started")) {
            trackApp.mClient.startTrace(trackApp.mTrace, traceListener);
            if (Constants.DEFAULT_PACK_INTERVAL != packInterval) {
                stopRealTimeLoc();
                startRealTimeLoc(packInterval);
            }
        } else {//如果换了手机，检测到有在进行中的任务，开始搜集轨迹任务
            String entityname = mSharedPreferencesHelper.getString(BaseConstants.DISPLAY_NAME) + "_" + mSharedPreferencesHelper.getString(BaseConstants.MOBILE_PHONE);
            LogUtils.debugEInfo("entityname==" + entityname);
            trackApp.mTrace.setEntityName(entityname);
            trackApp.mClient.startTrace(trackApp.mTrace, traceListener);
            if (Constants.DEFAULT_PACK_INTERVAL != packInterval) {
                stopRealTimeLoc();
                startRealTimeLoc(packInterval);
            }
        }
    }

    static class RealTimeHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
        }
    }

    /**
     * 实时定位任务
     *
     * @author baidu
     */
    class RealTimeLocRunnable implements Runnable {

        private int interval = 0;

        public RealTimeLocRunnable(int interval) {
            this.interval = interval;
        }

        @Override
        public void run() {
            if (isRealTimeRunning) {
                trackApp.getCurrentLocation(entityListener, trackListener);
                realTimeHandler.postDelayed(this, interval * 1000);
            }
        }
    }

}
